package cn.snorlaxzjt.LBSserver.controller;

import cn.snorlaxzjt.LBSserver.common.BusinessCode;
import cn.snorlaxzjt.LBSserver.common.Result;
import cn.snorlaxzjt.LBSserver.po.page.TokenPage;
import cn.snorlaxzjt.LBSserver.service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/image")
public class ImageController {

    @Resource
    ImageService imageService;

    @PostMapping("/upload")
    public Result<Map<String,String>> uploadImage(@RequestParam("image") MultipartFile image){
        if (image.isEmpty()) {
            return BusinessCode.FAIL.toResult();
        }
        try {
            String uri = imageService.uploadImage(image);
            Map<String,String> map=new HashMap<String,String>() {
                {
                    put("uri",uri );
                }
            };
            return BusinessCode.SUCCESS.toResult(map);
        } catch (Exception e) {
            log.error("上传图片错误",e);
            return BusinessCode.FAIL.toResult();
        }
    }

    @GetMapping(value = "getUploadToken")
    public Result<TokenPage> getUploadToken(){
        return BusinessCode.SUCCESS.toResult(imageService.getUploadToken());
    }
}